package net.shopxx.controller.admin;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;

import net.shopxx.FileInfo.FileType;
import net.shopxx.Filter;
import net.shopxx.Filter.Operator;
import net.shopxx.Message;
import net.shopxx.constant.AccountsConstant;
import net.shopxx.entity.AccountsItem;
import net.shopxx.excel.excel.ExcelFile;
import net.shopxx.pager.AccountsPageable;
import net.shopxx.pager.Page;
import net.shopxx.service.AccountsService;
import net.shopxx.service.AdminService;
import net.shopxx.service.FileService;
import net.shopxx.util.JsonUtils;

/**
 * Controller - 账务操作
 * 
 * @author frankie
 * @version 3.0
 */
@Controller("adminAccountsController")
@RequestMapping("/admin/accounts")
public class AccountsController extends BaseController {

	@Resource(name = "accountsServiceImpl")
	private AccountsService accountsService;

	@Resource(name = "fileServiceImpl")
	private FileService fileService;

	@Resource(name = "adminServiceImpl")
	private AdminService adminService;

	@Autowired
	private ServletContext servletContext;

	private static final String TB_ORDER_LABLE = "买家会员名";
	private Log log = LogFactory.getLog(this.getClass());

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(AccountsPageable pageable, ModelMap model) {
		List<Filter> filters = new ArrayList<Filter>();
		if (StringUtils.isNotBlank(pageable.getOrderType())) {
			Filter filter = new Filter();
			filter.setProperty(AccountsConstant.ANALYZED_ORDER_TYPE_PROPERTY);
			filter.setOperator(Operator.eq);
			filter.setValue(pageable.getOrderType());
			filters.add(filter);
		}

		if (StringUtils.isNotBlank(pageable.getStoreId())) {
			Filter filter = new Filter();
			filter.setProperty(AccountsConstant.ANALYZED_STORE_ID_PROPERTY);
			filter.setOperator(Operator.eq);
			filter.setValue(pageable.getStoreId());
			filters.add(filter);
		}

		if (StringUtils.isNotBlank(pageable.getOrderStatus())) {
			Filter filter = new Filter();
			filter.setProperty(AccountsConstant.ANALYZED_ORDER_STATUS_PROPERTY);
			if (Integer.valueOf(pageable.getOrderStatus()) == AccountsConstant.TB_ORDER_STATUS_NORMAL) {
				filter.setOperator(Operator.eq);
				filter.setValue(AccountsConstant.TB_ORDER_STATUS_NORMAL);
			} else {
				filter.setOperator(Operator.ne);
				filter.setValue(AccountsConstant.TB_ORDER_STATUS_NORMAL);
			}

			filters.add(filter);
		}

		pageable.setFilters(filters);
		Page<AccountsItem> ai = accountsService.findPage(pageable);
		model.addAttribute("page", ai);

		return "/admin/accounts/list";
	}

	/**
	 * 统计
	 */
	@RequestMapping(value = "/statistics", method = RequestMethod.GET)
	public String statistics(AccountsPageable pageable, ModelMap model) {

		Page<AccountsItem> ai = accountsService.findStatsPage(pageable);
		model.addAttribute("page", ai);
		model.addAttribute("label", true);

		Float sum = accountsService.findStatsSum(pageable);
		Long count = accountsService.findStatsCount(pageable);

		if (sum != null) {
			BigDecimal s = new BigDecimal(sum);
			model.addAttribute("sum", s.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
		} else {
			model.addAttribute("sum", 0);
		}
		model.addAttribute("count", count);

		List<String> admins = adminService.getAllAdminNames();
		model.addAttribute("admins", admins);

		return "/admin/accounts/statistics";
	}

	/**
	 * 解析文档
	 */
	@RequestMapping(value = "/analyze", method = RequestMethod.POST, produces = "text/html; charset=UTF-8")
	public String upload(FileType fileType, MultipartFile file, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		if (!fileService.isValid(fileType, file)) {
			data.put("message", Message.warn("admin.upload.invalid"));
		} else {
			try {
				// 获取操作的文件
				String path = servletContext.getRealPath("");
				ExcelFile ef = new ExcelFile(file.getInputStream(), path);
				ef.createStreamReadBook();
				String label = ef.get(AccountsConstant.FIRST_PAGE, AccountsConstant.LABEL_ROW, AccountsConstant.LABEL_COLUM);

				if (StringUtils.isNotBlank(label) && TB_ORDER_LABLE.equals(label)) {
					ef.generateExcel(AccountsConstant.TB_ORDER_KEY);
					accountsService.dealWithTbOrder(ef);
				}

			} catch (IOException e) {
				log.error("分析淘宝excel订单出错：" + Message.warn("admin.upload.invalid"));
				data.put("message", Message.warn("admin.upload.invalid"));
			}
		}

		if (data.isEmpty()) {
			return "redirect:list.jhtml";
		} else {
			try {
				response.setContentType("text/html; charset=UTF-8");
				JsonUtils.writeValue(response.getWriter(), data);
			} catch (IOException e) {
				log.error("分析淘宝excel订单，转换json流出错：" + e.getStackTrace());
			}
			return null;
		}
	}

}
